package com.lsec.springbootinit.model.common;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.lsec.springbootinit.model.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 登录用户
 *
 * @author Cherry
 * @date 2023/06/12
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {


    public LoginUser(SysUser sysUser) {
        this.sysUser = sysUser;
    }

    public LoginUser(SysUser sysUser, List<String> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
    }

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 用户类型
     */
    private Integer userType;

    /**
     * 租户编号
     */
    private Long tenantId;

    /**
     * 登录时间
     */
    private Long loginTime;

    /**
     * 刷新令牌时间
     */
    private Long refreshTime;

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 授权范围
     */
    private List<String> scopes;


    /**
     * 权限
     */
    private List<String> permissions;


    /**
     * 系统用户
     */
    private SysUser sysUser;




    /**
     * 角色
     */
    //private transient List<Role> roleList;

    /**
     * 存储SpringSecurity所需要的权限信息的集合
     */
    @JsonIgnore
    private List<GrantedAuthority> authorities;

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null){
            return authorities;
        }
        authorities = AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));
        return authorities;
    }

    @Override
    @JsonIgnore
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    @JsonIgnore
    public String getUsername() {
        return sysUser.getUsername();
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }
}